<template>
  <el-card shadow="hover" class="usage-container">
    <!-- 搜索栏 -->
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="疫苗编号">
        <el-input
          v-model="searchForm.vaccineNumbering"
          placeholder="输入疫苗编号"
          clearable
        />
      </el-form-item>
      <el-form-item label="时间范围">
        <el-date-picker
          v-model="searchForm.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchUsageData">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格展示 -->
    <el-table
      :data="usageList"
      border
      style="width: 100%; margin-top: 20px"
      v-loading="loading"
    >
      <el-table-column
        label="序号"
        type="index"
        width="60"
        :index="(index) => (page - 1) * pageSize + index + 1"
      />
      <el-table-column prop="vaccineNumbering" label="疫苗编号" />
      <el-table-column prop="quantityUsed" label="领取数量" />
      <el-table-column
        prop="usageTime"
        label="领取时间"
        :formatter="formatDate"
      />
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :current-page="page"
        @current-change="handlePageChange"
      />
    </div>
  </el-card>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import dayjs from 'dayjs'

const usageList = ref([]) // 当前页展示数据
const allUsageData = ref([]) // 原始数据
const filteredData = ref([]) // 前端过滤后数据
const total = ref(0)
const page = ref(1)
const pageSize = ref(5)
const loading = ref(false)

const searchForm = reactive({
  vaccineNumbering: '',
  dateRange: [],
})

const fetchUsageData = async () => {
  loading.value = true
  try {
    const doctor = JSON.parse(localStorage.getItem('user') || '{}')
    const doctorId = doctor.id
    const params = {
      doctorId,
      page: 1,
      size: 1000, // 获取全部数据
    }

    const { data } = await axios.get(
      'http://127.0.0.1:8181/vaccineUsage/list',
      { params }
    )

    allUsageData.value = data.data?.data || []
    applyFilterAndSort()
  } catch (err) {
    console.error('获取数据失败', err)
  } finally {
    loading.value = false
  }
}

const applyFilterAndSort = () => {
  let list = [...allUsageData.value]

  // 疫苗编号前端模糊过滤
  if (searchForm.vaccineNumbering) {
    list = list.filter((item) =>
      item.vaccineNumbering.includes(searchForm.vaccineNumbering)
    )
  }

  // 时间范围过滤
  if (searchForm.dateRange.length === 2) {
    const [start, end] = searchForm.dateRange
    const startTime = new Date(start).getTime()
    const endTime = new Date(end).getTime()
    list = list.filter((item) => {
      const time = new Date(item.usageTime).getTime()
      return time >= startTime && time <= endTime
    })
  }

  // 按编号排序
  filteredData.value = list.sort((a, b) =>
    a.vaccineNumbering.localeCompare(b.vaccineNumbering)
  )

  total.value = filteredData.value.length
  page.value = 1
  updatePageData()
}

const updatePageData = () => {
  const start = (page.value - 1) * pageSize.value
  const end = start + pageSize.value
  usageList.value = filteredData.value.slice(start, end)
}

const handlePageChange = (newPage) => {
  page.value = newPage
  updatePageData()
}

const resetSearch = () => {
  searchForm.vaccineNumbering = ''
  searchForm.dateRange = []
  page.value = 1
  applyFilterAndSort()
}

const formatDate = (row, column, cellValue) =>
  cellValue ? dayjs(cellValue).format('YYYY-MM-DD HH:mm') : ''

onMounted(fetchUsageData)
</script>

<style scoped>
.usage-container {
  padding: 20px;
}
.search-form {
  margin-bottom: 10px;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
